﻿using System.Collections.Generic;
using System.Text;
using System.Net;

namespace mVu
{
  public class CookieManager
  {
    private Dictionary<string, string> _cookieValues;

    public Dictionary<string, string> CookieValues
    {
      get { return _cookieValues ?? (_cookieValues = new Dictionary<string, string>()); }
    }

    public void PublishCookies(HttpWebRequest webRequest)
    {
      var sb = new StringBuilder();
      sb.Append("Cookie: ");
      foreach (var key in CookieValues.Keys)
      {
        sb.Append(key);
        sb.Append("=");
        sb.Append(CookieValues[key]);
        sb.Append("; ");
        sb.Append("$Path=\"/\"; ");
      }

      webRequest.Headers.Add(sb.ToString());
    }

    public void StoreCookies(HttpWebResponse webResponse)
    {
      for (var x = 0; x < webResponse.Headers.Count; x++)
      {
        if (webResponse.Headers.Keys[x].ToLower().Equals("set-cookie"))
        {
          AddRawCookie(webResponse.Headers[x]);
        }
      }
    }

    private void AddRawCookie(string rawCookieData)
    {
      string key = null;
      string value = null;

      string[] entries;

      if (rawCookieData.IndexOf(",") > 0)
      {
        entries = rawCookieData.Split(',');
      }
      else
      {
        entries = new[] { rawCookieData };
      }

      foreach (var entry in entries)
      {
        var cookieData = entry.Trim();

        if (cookieData.IndexOf(';') > 0)
        {
          var temp = cookieData.Split(';');
          cookieData = temp[0];
        }

        var index = cookieData.IndexOf('=');
        if (index > 0)
        {
          key = cookieData.Substring(0, index);
          value = cookieData.Substring(index + 1);
        }

        if (key != null && value != null)
        {
          CookieValues[key] = value;
        }
      }
    }

    public override string ToString()
    {
      var sb = new StringBuilder();
      sb.Append("[");
      foreach (var key in CookieValues.Keys)
      {
        sb.Append("{");
        sb.Append(key);
        sb.Append(",");
        sb.Append(CookieValues[key]);
        sb.Append("}, ");
      }
      if (CookieValues.Keys.Count > 0)
      {
        sb.Remove(sb.Length - 2, 2);
      }
      sb.Append("]");

      return sb.ToString();
    }
  }
}
